<template>
    <div class="app-container" v-loading="loading" style="overflow-x: hidden">
      <el-form :model="form" ref="formRef" :inline="true" :rules="rules" label-width="130px" :disabled="parentType == 'view'">
        <el-form-item label="工厂" prop="factory">
          <el-select v-if="parentType == 'add'" v-model="form.factory" placeholder="请选择" style="width: 240px" clearable filterable @change="handleSearchListChange('factory')" :disabled="parentType == 'update'">
            <el-option v-for="(item, index) in factoryOptions" :key="index" :label="item.deptName" :value="item.deptCode"> </el-option>
          </el-select>
          <el-tooltip v-else :content="form.factoryName" placement="top">
              <p class="showDetail">{{ form.factoryName }}</p>
          </el-tooltip>
          
        </el-form-item>
        <el-form-item label="工段" prop="workshopCode">
          <el-select
            v-if="parentType == 'add'" 
            v-model="form.workshopCode"
            placeholder="请选择"
            clearable
            filterable
            style="width: 240px"
            @change="handleSearchListChange('workSection')"
            :disabled="parentType == 'update'">
            <el-option v-for="(item, index) in workshopOptions" :key="index" :label="item.deptName" :value="item.deptCode"> </el-option>
          </el-select>
          <el-tooltip v-else :content="form.workshopName" placement="top">
              <p class="showDetail">{{ form.workshopName }}</p>
          </el-tooltip>
          
        </el-form-item>
        <el-form-item label="产线" prop="lineCode">
          <el-select
            v-model="form.lineCode"
            v-if="parentType == 'add'" 
            placeholder="请选择"
            clearable
            filterable
            style="width: 240px"
            @change="handleSearchListChange('lineCode')"
            :disabled="parentType == 'update'">
            <el-option v-for="(item, index) in lineOptions" :key="index" :label="item.deptName" :value="item.deptCode"> </el-option>
          </el-select>
          <el-tooltip v-else :content="form.lineName" placement="top">
              <p class="showDetail">{{ form.lineName }}</p>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="工艺段" prop="sectionCode">
          <el-select
            v-model="form.sectionCode"
            v-if="parentType == 'add'" 
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="width: 240px"
            @change="handleSearchListBlur('sectionCode')"
            :disabled="parentType == 'update'">
            <el-option v-for="(item, index) in processOptions" :key="index" :label="item.deptName" :value="item.deptCode"> </el-option>
          </el-select>
          <el-tooltip v-else :content="form.sectionName" placement="top">
              <p class="showDetail">{{ form.sectionName }}</p>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="生产日期" prop="prodDate">
          <el-date-picker
              v-if="parentType == 'add'" 
            v-model="form.prodDate"
            type="date"
            placeholder="请选择生产日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            :disabled="parentType == 'update'"
            @change="getChangeShifts()">
          </el-date-picker>
          <el-tooltip v-else :content="form.prodDate" placement="top">
              <p class="showDetail">{{ form.prodDate }}</p>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="班次" prop="classesName">
          <el-select v-if="parentType == 'add'"  v-model="form.classesName" placeholder="请选择" style="width: 240px" clearable filterable @change="handleClassesCode" :disabled="parentType == 'update'">
            <el-option v-for="(item, index) in shiftGroupsList" :key="index" :label="item.scheduleName" :value="item.scheduleName"> </el-option>
          </el-select>
          <el-tooltip v-else :content="form.classesName" placement="top">
              <p class="showDetail">{{ form.classesName }}</p>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="班组" prop="workGroupName">
          {{ form.workGroupName }}
        </el-form-item>
        <el-form-item label="生产订单" style="width: 100%">
          <el-table class="wordOrderListClass" :data="workOrderList" ref="workOrderListRef" @select="workOrderListChange"  row-key="id" border style="width: 100%; margin-top: 10px">
            <el-table-column v-if="parentType == 'add'"  type="selection" width="55" />
            <el-table-column label="订单编号" prop="orderCode" />
            <el-table-column label="产品名称" prop="prodName" />
            <el-table-column label="当班产量" prop="onDutyOutput" />
            <el-table-column label="单位" prop="onDutyUnit" />
          </el-table>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="当前投料" name="first">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button v-if="parentType != 'view'" type="primary" icon="plus" @click="handleAddWhStorehouseInDetail">选择物料</el-button>
            </el-col>
          </el-row>
          <el-form ref="tableForm" :model="recipeMaterialList" label-width="0">
            <el-table :data="recipeMaterialList" :header-cell-class-name="start" maxHeight="400" border  ref="whStorehouseInDetail">
              <el-table-column min-width="150px" label="投料内容" prop="matName" />
              <el-table-column min-width="120px" label="物料编号" prop="matCode" />
              <el-table-column min-width="120px" label="投料批号" prop="feedingBatchNo" />
              <el-table-column min-width="120px" label="线边仓" prop="storehouseName" />
              <el-table-column min-width="120px" label="库位" prop="binName" />
              <el-table-column min-width="180px"  label="投入数量" prop="inputQty" >
                <template #default="scope">
                  <el-input-number :disabled="parentType == 'view'"  style="width: 100%" :min="1" :precision="2" v-model="scope.row.inputQty" controls-position="right"> </el-input-number>
              </template>
              </el-table-column>
              <el-table-column width="80px" label="单位" prop="inputUnit" />
  
              <el-table-column label="投料时间" min-width="180px" prop="feedingTime" >
                <template #default="scope">
                  <el-date-picker :disabled="parentType == 'view'"  v-model="scope.row.feedingTime" value-format="YYYY-MM-DD HH:mm:ss"
                  :editable="false" :clearable="false" style="width: 100%" type="datetime" placeholder="选择投料时间" />
                </template>
              </el-table-column>
  
              <el-table-column width="100px" v-if="parentType != 'add'" label="操作人" prop="operator" />
              <el-table-column width="180px" v-if="parentType != 'add'" label="记录时间" prop="recordTime" />
  
              <el-table-column width="100px" v-if="parentType != 'view'" label="操作" align="center" fixed="right" minWidth="100" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Delete" v-hasPermi="['tech:recipeDetail:remove']" @click="handleDeleteWhStorehouseInDetail(scope.row, scope.$index)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
        <!-- <el-tab-pane label="当班投料记录" name="second">
          <p>暂无</p>
        </el-tab-pane> -->
      </el-tabs>
      <!-- <UserSelect ref="userSelect" :showInput="false" placeholder="请选择岗位人员" :multiple="true" title="选择岗位人员" @submits="handleChange"></UserSelect> -->
  
      <!-- <workOrderList
        @changeWorkOrderList="changeWorkOrderList"
        :title="'选择生产工单'"
        :openWorkOrder="openWorkOrder"
        :sectionList="sectionList"
        :sectionCodeList="form.sectionCode"></workOrderList> -->
  <!-- :erpOrderNo="" -->
      <matDialog v-model="show"  :factory="form.factory"  :workshop="form.workshopCode" :line="form.lineCode" :section="form.sectionCode" @change="handleChange"></matDialog>
    </div>
  </template>
  
  <script setup name="changeShifts">
  import { listChangeShifts} from '@/api/productionMgt/changeShifts'
  import { getScheduleNames4ChangeShifts } from '@/api/base/plan/shiftMgt/shiftCalendar'
  import { listShiftGroup } from '@/api/base/plan/shiftMgt/shiftGroup'
  import { getFactoryTree, depeIdSelectList } from '@/api/system/dept'
  import { planGroupDetail } from '@/api/base/plan/shiftMgt/shiftGroup'
  import { getFeeding ,getProdOrder} from '@/api/productionMgt/feeding'
  import matDialog from "@/components/matDialog/matDialog.vue";
  import { ref,nextTick, reactive, useAttrs,getCurrentInstance,onMounted } from 'vue'
  const attrs = useAttrs()
  const { proxy } = getCurrentInstance()
  const parentType = ref('add')
  const workGroupOptions = ref([])
  const loading = ref(false)
  const activeName = ref('first')
  const shiftGroupsList = ref([])
  const previousClassInfo = ref([])
  const prodChangeShiftsMemberList = ref([])
  const recipeMaterialList = ref([])
  var factoryOptions = ref([])
  var workshopOptions = ref([])
  var lineOptions = ref([])
  var processOptions = ref([])
  const workOrderList = ref([])
  const workOrderListRef = ref()
  const show = ref(false)
  const emit = defineEmits(['close', 'setTitle', 'setActions', 'setIsActionTop'])
  const data = reactive({
    form: {},
    rules: {
      factory: [{ required: true, message: '工厂不能为空', trigger: 'change' }],
      workshopCode: [{ required: true, message: '工段不能为空', trigger: 'change' }],
      lineCode: [{ required: true, message: '产线不能为空', trigger: 'change' }],
      sectionCode: [{ required: true, message: '工艺段不能为空', trigger: 'blur' }],
      prodDate: [{ required: true, message: '生产日期不能为空', trigger: 'change' }],
      classesName: [{ required: true, message: '班次不能为空', trigger: 'change' }],
      startProdTime: [{ required: true, message: '开始生产时间不能为空', trigger: 'change' }],
      workOrderList: [{ required: true, message: '生产订单不能为空', trigger: 'change' }],
    },
  })
  
  const { form, rules } = toRefs(data)
  const start = ({ columnIndex }) => {
    if (columnIndex == 7 ||columnIndex == 5) {
      return "start";
    }
  };
  /** 物料入仓明细添加按钮操作 */
  function handleAddWhStorehouseInDetail() {
    show.value = true
  }
  // 查询交接班当前班组名称
  function getWorkName(){
    let obj = {
      pageNum: 1,
      pageSize: 1000,
      status: 1,
      factory: form.value.factory,
      workshopCode: form.value.workshopCode,
      productLine: form.value.lineCode,
      sectionCode: form.value.sectionCode,
      startTime4CarryOn: form.value.prodDate,
      endTime4CarryOn: form.value.prodDate,
      scheduleName:form.value.classesName,
    }
    listChangeShifts(proxy.addDateRange(obj)).then((response) => {
      console.log(response);
      if(response && response.rows && response.rows.length){
        form.value.workGroupName = response.rows[0].workGroupName || '-'
      } else {
        form.value.workGroupName = '-'
      }
    });
  }
  
  function getDetail(id) {
    loading.value = true
    getFeeding(id).then((res) => {
        form.value = res.data;
        workOrderList.value = [{
          orderCode:form.value.orderCode,
          prodName : form.value.prodName,
          onDutyOutput : form.value.onDutyOutput,
          onDutyUnit : form.value.onDutyUnit
        }]
        recipeMaterialList.value = [
          {
              ...form.value
          }
        ]
        recipeMaterialList.value.id = ''
      loading.value = false
    })
  }
  function handleChange(val) {
    if (val.length) {
      if(parentType.value =='update' && val.length>1){
          return proxy.$modal.msgError('最多选择一条物料')
      }
      val.forEach((item) => {
        item.feedingBatchNo = item.batchNo;
        item.inputUnit = item.packageUnit;
        item.feedingTime = proxy.parseTime(new Date());
      })
    }
    recipeMaterialList.value = val
  }
  
  
  function getProdOrderList(){
      workOrderList.value = []
      if(form.value.classesName && form.value.prodDate && form.value.sectionCode){
          const data = {
              classesName:form.value.classesName,
              prodDate:form.value.prodDate,
              sectionCode:form.value.sectionCode,
          }
          getProdOrder(data).then((res) => {
              workOrderList.value = res.rows
              if(workOrderList.value.length){
                  nextTick(() => {
                      workOrderListRef.value.toggleRowSelection(workOrderList.value[0], true);
                  })
              }
          })
      }
  }
  /** 物料明细删除按钮操作 */
  function handleDeleteWhStorehouseInDetail(row, index) {
    proxy.$modal
      .confirm("是否确认删除所选数据项？")
      .then(() => {
          recipeMaterialList.value.splice(index, 1);
          proxy.$modal.msgSuccess("移除成功");
      })
      .catch(() => {});
  }
  function workOrderListChange(selection,row){
      let selected = selection.length && selection.indexOf(row) !== -1
      workOrderListRef.value.clearSelection();
      if(selected){
          nextTick(() => {
              workOrderListRef.value.toggleRowSelection(row, true);
              console.log(workOrderListRef.value.getSelectionRows());
          })
      } else {
          nextTick(() => {
              workOrderListRef.value.toggleRowSelection(row, false);
              console.log(workOrderListRef.value.getSelectionRows());
          })
      }
      console.log(workOrderListRef.value.getSelectionRows());
  }
  
  
  function handleSearchListChange(type) {
    if (type == 'factory') {
      depeIdSelectList({
        deptType: 'station',
        deptCode: form.value.factory,
      }).then((res) => {
        workshopOptions.value = res.data
        lineOptions.value = []
        processOptions.value = []
        if (!form.value.id) {
          form.value.workshopCode = ''
          form.value.lineCode = ''
          form.value.sectionCode = ''
        }
      })
    }
    if (type == 'workSection') {
      depeIdSelectList({
        deptType: 'line',
        deptCode: form.value.workshopCode,
      }).then((res) => {
        lineOptions.value = res.data
        processOptions.value = []
        if (!form.value.id) {
          form.value.lineCode = ''
          form.value.sectionCode = ''
        }
      })
    }
    if (type == 'lineCode') {
      depeIdSelectList({
        deptType: 'craft',
        deptCode: form.value.lineCode,
      }).then((res) => {
        processOptions.value = res.data
        if (!form.value.id) {
          form.value.sectionCode = ''
        }
      })
    }
  }
  
  function handleSearchListBlur(type) {
    if (form.value.sectionCode && form.value.sectionCode.length > 0) {
      // 班次列表
      getChangeShifts()
      // // 上一班信息
      // getPreviousClassInfo()
      // 本班人员安排
      getPlanGroupDetail()
      // 班组下拉列表
      getWorkGroupData()
    } else {
      // 班次列表为空
      shiftGroupsList.value = []
      // 上一班信息列表为空
      previousClassInfo.value = []
      // 本班人员安排列表为空
      prodChangeShiftsMemberList.value = []
      // 班组下拉列表为空
      workGroupOptions.value = []
      // 班次为空
      form.value.classesName = ''
      // 开始生产时间为空
      form.value.startProdTime = ''
    }
    getProdOrderList()
  }
  
  function getWorkGroupData() {
    listShiftGroup({ sectionCode: form.value.sectionCode.toString() }).then((res) => {
      workGroupOptions.value = res.rows
    })
  }
  
  function getChangeShifts() {
    console.log(form.value.prodDate, form.value.sectionCode, '======form.prodDate')
    getProdOrderList()
    if (form.value.prodDate && form.value.sectionCode) {
      form.value.classesName = ''
      form.value.startProdTime = ''
      const today = form.value.prodDate
      const year = today.substring(0, 4)
      const month = today.substring(5, 7)
      const day = today.substring(8)
      const deptId =
        factoryOptions.value.find((item) => {
          return item.deptCode == form.value.factory
        })?.deptId || ''
      getScheduleNames4ChangeShifts({
        sectionCodeList: [form.value.sectionCode],
        yearStr: year,
        monthStr: month,
        dayNo: day,
        deptId,
      }).then((res) => {
        shiftGroupsList.value = res.data
        form.value.classesName =
          res.data.find((item) => {
            return item.def
          })?.scheduleName || ''
        form.value.classesCode =
          res.data.find((item) => {
            return item.def
          })?.classesCode || ''
        form.value.startProdTime =
          res.data.find((item) => {
            return item.def
          })?.startTime || ''
          getWorkName()
          // shiftGroupsList.value.forEach((el) => {
          //   if (el.scheduleName == form.value.classesName) {
          //     form.value.workGroupName = el.workGroupName ||'-'
          //   }
          // })
  
          // 查询生产订单
          getProdOrderList()
      }).catch((msg)=>{
        proxy.$modal.msgError(msg.replace('接班','投料'))
      })
    }
  }
  function getPlanGroupDetail() {
    planGroupDetail({ section: form.value.sectionCode.toString() }).then((res) => {
      prodChangeShiftsMemberList.value = res.data
    })
  }
  
  function handleClassesCode(val) {
    shiftGroupsList.value.forEach((el) => {
      if (el.scheduleName == val) {
        form.value.startProdTime = el.startTime || ''
        form.value.classesCode = el.classesCode
        // form.value.workGroupName = el.workGroupName ||'-'
      }
      getWorkName()
      console.log(form.value, '====form.value')
    })
    // 查询生产订单
    getProdOrderList()
  }
  
  function cancel() {
    emit('close')
  }
  
  onMounted(async () => {
    const { data } = attrs
    parentType.value = 'view'
    if (data?.mainTableId) {
      getDetail(data.mainTableId.replace('投料id:',''))
    }
  })
  </script>
  <style  lang="scss"  scoped>
  :deep(.el-table table tr th.start div:before) {
    content: "*";
    color: red;
  }
  .showDetail{
      width: 240px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 0;
  }
  </style>
  